package com.eairlv.route.client.configuration;

import com.eairlv.route.client.interceptor.RouteInterceptor;
import com.eairlv.route.client.interceptor.SimpleRouteInterceptor;
import com.eairlv.route.client.service.RouteClientService;
import com.eairlv.route.client.service.RouteLoadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 *
 * @author eairlv
 * @description
 * @date 11:08 2019/12/9
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "route.client", value = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(RouteProperties.class)
public class RouteAutoConfiguration {

    @Autowired
    RouteProperties routeProperties;

    @Autowired(required = false)
    RouteInterceptor routeInterceptor;

    @Qualifier("routeTemplate")
    @Resource
    private RestTemplate routeTemplate;

    @Bean
    @LoadBalanced
    public RestTemplate routeTemplate() {
        return new RestTemplate();
    }

    @Bean
    @ConditionalOnBean(RestTemplate.class)
    RouteClientService routeClientService(){
        return new RouteClientService(routeProperties, routeTemplate);
    }

    @Bean
    @ConditionalOnBean(RouteClientService.class)
    public RouteLoadService RouteLoadService(RouteClientService routeClientService){
        if (routeInterceptor == null){
            return new RouteLoadService(routeClientService, new SimpleRouteInterceptor());
        } else {
            return new RouteLoadService(routeClientService, routeInterceptor);
        }
    }
}
